package cn.bdqn.controller;

import cn.bdqn.bean.result.Result;
import cn.bdqn.bean.result.ResultGenerator;
import cn.bdqn.domain.Druginfo;
import cn.bdqn.domain.Recipe;
import cn.bdqn.service.DrugInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/doctor/recipe")
public class RecipeController {

    @Autowired
    private DrugInfoService drugInfoService;

    @Autowired
    private RedisTemplate redisTemplate;


    @RequestMapping("/getDrugInfo/{type}")
    public Result getDrugInfo(@PathVariable String type, Map<String,Object> map) throws Exception{
        try{
            if (type == null || "".equals(type.trim())){
                List<Druginfo> druginfos = drugInfoService.queryAll();
                map.put("drugInfos",druginfos);
            }else{
                List<Druginfo> druginfos = drugInfoService.queryByType(type);
                map.put("drugInfos",druginfos);
            }
            return ResultGenerator.genSuccessResult(map);
        }catch (Exception e){
            return ResultGenerator.genFailResult("出现异常!");
        }

    }


    /**
     * 查询药品信息根据药品名  (模糊查询)
     * @param name 药品名
     * @return
     * @throws Exception
     */
    @RequestMapping("getDrugInfoByNameLike/{name}")
    public Result getDrugByName(@PathVariable String name,Map<String,Object> map) throws Exception {
        try {
            List<Druginfo> druginfos = drugInfoService.queryByNameLike(name);
            map.put("drugInfos",druginfos);
            return ResultGenerator.genSuccessResult(map);
        }catch (Exception e){
            return ResultGenerator.genFailResult("查询异常");
        }
    }


    /**
     * 添加一条处方
     * @param recipe 处方 信息
     * @return
     * @throws Exception
     */
    @RequestMapping("/addRecipe")
    public Result addRecipe(Recipe recipe) throws Exception {
        try {
            String regId = (String) redisTemplate.boundValueOps("RegistrationId").get();
            recipe.setRegisId(regId);
            int i =  drugInfoService.addRecipe(recipe);
            if (i > 0){
                return ResultGenerator.genFailResult("已添加处方！");
            }else {
                return ResultGenerator.genFailResult("处方添加失败!");
            }
        }catch (Exception e){
            e.printStackTrace();
            return ResultGenerator.genFailResult("插入信息异常!");
        }
    }
}
